<?php
class UserModel extends Model
{

    const ROLE_USER = 0;
    const ROLE_MANAGER = 1;
    const ROLE_ADMIN = 2;

    const STATUS_ACTIVE = 1;
    const STATUS_DELETED = 0;

    public $rules = array(
        'id' => array('required'),
        'name' => array('required'),
        'email' => array('required'),
        'city_id' => array('required'),
        'phone' => array('required'),
        'status' => array('required'),
        'role' => array('required'),
        'create_date' => array('required'),
        'password_token' => array('required'),
        'password_hash' => array('required'),
    );
    public $attributes = array();
    public $tableName = 'user';

    public function beforeSave()
    {
        $this->attributes['create_date'] = date('Y-m-d H:i:s');
        $this->attributes['password_token'] = md5(time());
    }

    public function afterSave()
    {
        $message = '<html>
        <head>
            <title>Birthday Reminders for August</title>
        </head>
        <body>
        <h2>Поздравляем!</h2>
        <p>Вы успешно зарегистрировались. Для подтверждения перейдите по ссылке:
        <a href="http://dribble/user/recovery/' . $this->attributes['password_token'] . '"></a>
        </p>

        </body>
        </html>';

        $headers = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
        $headers .= 'From: Dribble Service <dribble@dribble.com>' . "\r\n";

        if (mail($this->attributes['email'], 'Поздравляем!', $message, $headers))
            return true;
    }

    public function getUser($id)
    {
        return $this->getOne("SELECT * FROM {$this->tableName} WHERE id=:id", array(':id' => (int)$id));
    }

    public function getUserByEmail($email)
    {
        return $this->getOne("SELECT * FROM {$this->tableName} WHERE email=:email", array(':email' => $email));
    }

    public function getUserByToken($token)
    {
        return $this->getOne("SELECT * FROM {$this->tableName} WHERE password_token=:password_token", array(':password_token' => $token));
    }

    public function getAdditionalProducts()
    {
        return $this->getAll("SELECT * FROM {$this->tableName} WHERE type=:type", array(':type' => self::ADDITIONAL_PRODUCT));
    }
}